<template>
<li :class="[$style.container]" :style="[hiddenStyle]">

<div :class="[$style.inputWrap]">
  <slot name="prepend"></slot>
  <input v-model="value" type="text" :class="[$style.input]" ref="input">
  <div :class="[$style.actions]">
    <el-link :underline="false" type="success" :disabled="!value" @click="onConfirm">
      <i class="el-icon-check ft-lg" v-if="!submitting"></i>
      <i class="el-icon-loading ft-lg" v-else></i>
    </el-link>
    <el-link :underline="false" type="info" class="ml-2" @click="onCancel"><i class="el-icon-close ft-lg"></i></el-link>
  </div>
</div>
</li>
</template>

<script lang="ts">

import { Vue, Component, Prop, Emit, Inject, Ref } from 'vue-property-decorator'

@Component
export default class InlineInput extends Vue {
  @Ref() input!: HTMLDivElement

  @Prop() beforeConfirmFn!: (value: string) => Promise<any>

  visible = false

  resolve: any = null

  reject: any = null

  value = ''

  submitting = false

  get hiddenStyle () {
    return !this.visible ? { display: 'none' } : {}
  }

  open (value: string): Promise<string> {
    this.value = value || ''
    this.visible = true
    this.$nextTick(() => {
      if (this.input) this.input.focus()
    })
    return new Promise((resolve, reject) => {
      this.resolve = resolve
      this.reject = reject
    })
  }

  onConfirm () {
    const handler = () => {
      this.visible = false
      if (this.resolve) this.resolve(this.value)
    }
    if (this.beforeConfirmFn) {
      this.submitting = true
      this.beforeConfirmFn(this.value).then(() => {
        handler()
      }).catch(() => {
        // ignore
      }).finally(() => {
        this.submitting = false
      })
    } else {
      handler()
    }
  }

  onCancel () {
    this.visible = false
    if (this.reject) this.reject()
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.inputWrap {
  position: relative;
}

.input {
  padding-right: 46px;
  box-sizing: border-box;
  line-height: 24px;
  border: 1px solid $text-secondary-color;

  &:active, &:focus {
    outline: 0;
    border: 1px solid $color-primary;
  }

  &:focus {
    border: 1px solid $color-primary;
  }
}

.actions {
  position: absolute;
  right: 4px;
  top: 50%;
  transform: translateY(-50%);
}
</style>
